import store from '../modules/store'
import config from '../config'
import frd from '../modules/formatRequestData'
import tool from './tool'
import formatRequestData from '../modules/formatRequestData'
import { LPAPIFactory, LPAUtils } from "../utils/lpapi-ble/index";
import printTaskHandler from './printTaskHandler'

let closeLoadingKey = false
let requesting = false

export default {
  updateWindowInfo() {
    let titleBarHeight = '45px'
    let navigateBarHeight = '170rpx'

    let re = wx.getSystemInfoSync()
    re = re.statusBarHeight
    store.setItem('windowInfo', {
      statusBarHeight: `${re}px`,
      titleBarHeight,
      navigateBarHeight,
      contentHeight: `calc(100vh - ${re}px - ${navigateBarHeight})`,
      contentHeightWithoutTitleBar: `calc(100vh - ${re}px - ${titleBarHeight} - ${navigateBarHeight})`,
    })
  },
  wait(n) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        return resolve()
      }, n * 1000);
    })
  },
  updateMainCurrentPageIndex(index) {
    store.setItem('mainCurrentPageIndex', index)
  },
  requestData(apiName = '', data = {}, method = 'post', showLoading = true) {
    let apiName_c = apiName
    return new Promise((resolve, reject) => {
      requesting = true
      let t
      if (showLoading && store.getItem('requestShowLoading')) {
        closeLoadingKey = false
        t = setTimeout(() => {
          wx.showLoading({
            title: '请稍候',
            mask: true
          })
        }, 0)
      }
      data = formatRequestData.formatBeforeSend(apiName, data)
      if (method == 'get') {
        apiName += this.qsStringify(data)
      }
      console.log('HTTPS - 开始', apiName)
      wx.request({
        url: config.serverURL + apiName,
        method,
        header: {
          token: (store.getItem('userData') ? store.getItem('userData').token : undefined)
        },
        data: (method == 'post' ? data : undefined),
        mask: true,
        fail(e) {
          wx.hideLoading()
          console.log('请求失败：', e)
          resolve({
            status: 0,
            content: '请求失败（非后端返回）'
          })
        },
        success(e) {
          clearTimeout(t)
          closeLoadingKey = true
          // setTimeout(() => {
          //   if (closeLoadingKey == false) return
          //   wx.hideLoading()
          // }, 50);
          wx.hideLoading()
          e.data.data = frd.format(apiName_c, e.data.data)
          console.log('HTTPS - 完成', apiName, e.data)
          if (e.data.status == -1) {
            wx.navigateBack({
              delta: 100
            })
            store.removeItem('userData')
            try {
              store.setItem('doNotReConnectWS', true)
              tool.webSocket.socketTask.close()
            } catch (error) {

            }
            store.setItem('mainCurrentPageIndex', -1)
            setTimeout(() => {
              store.setItem('mainCurrentPageIndex', 0)
              setTimeout(() => {
                wx.showModal({
                  title: '',
                  content: `${e.data.content}，请重新登录`,
                  showCancle: false,
                  complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {

                    }
                  }
                })
              }, 300);
            }, 100);
            return
          }
          resolve(e.data)
        }
      })
    })
  },
  qsStringify(data = {}) {
    let re = '?'
    for (let i = 0; i < Object.keys(data).length; i++) {
      let key = Object.keys(data)[i]
      let value = data[Object.keys(data)[i]]
      if (i) re += '&'
      re += `${key}=${value}`
    }
    return re
  },
  isLogined() {
    return store.getItem('userData') != undefined
  },
  async handleNotLogin() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  getLoginCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        complete: async (res) => {
          return resolve(res.code)
        }
      });
    })
  },
  handleLogin() {
    return new Promise(async (resolve, reject) => {
      wx.login({
        success: async (res) => {
          if (res.code) {
            let re = await this.requestData('/user/login', {
              code: res.code
            })
            if (re.status === 1) {
              store.setItem('openId', re.data.openId)
              store.setItem('userData', re.data)
              tool.webSocket.connect()
              return resolve(1)
            }
            if (re.status === -1) {
              this.handleShowModel(re.content)
              this.handleExitLogin()
            }
          } else {

          }

          return resolve(0)
        }
      });
    })
  },
  validatePhoneNumber(phone) {
    const regex = /^1[3-9]\d{9}$/;
    return regex.test(phone);
  },
  readFileToBase64(filePath) {
    const fs = wx.getFileSystemManager();
    return new Promise((resolve, reject) => {
      fs.readFile({
        filePath: filePath,
        encoding: 'base64',
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },
  uploadFileToServer(filePath) {
    return new Promise(async (resolve, reject) => {
      wx.showLoading({
        title: '正在上传',
        mask: true
      })
      wx.uploadFile({
        url: config.serverURL + '/file/upload',
        filePath: filePath,
        name: 'file',
        header: {
          token: (store.getItem('userData') ? store.getItem('userData').token : undefined)
        },
        success(res) {
          wx.hideLoading()
          return resolve(res.data)
          console.log('上传成功', res);
        },
        fail(error) {
          wx.hideLoading()
          return resolve({
            status: 0,
            content: '上传失败'
          })
          console.error('上传失败', error);
        }
      });
    })
  },
  handleShowToast(title, icon = 'auto', time = 1000) {
    wx.showToast({
      title,
      icon: icon == 'auto' ? ((() => {
        if (title.indexOf('成功') + 1) return 'success'
        if (title.indexOf('rror') + 1) return 'error'
      })()) : icon,
      duration: time
    })
  },
  handleShowToastWithMask(title, icon = 'none', time = 1000) {
    wx.showToast({
      title,
      icon,
      mask: true,
      duration: time
    })
  },
  async getUserInfo() {
    let loginCode = await this.getLoginCode()
    if (loginCode) {

    } else {
      return {
        status: 0,
        content: '无法获取Code'
      }
    }
  },
  async testConnection() {
    try {
      let re = await this.requestData('/test', {}, 'get')
      return re.data === true
    } catch (error) {
      return false
    }
  },
  handleShowModel(content = '', showCancel = true, okCallBack = () => { }, cancleCallBack = () => { }) {
    wx.showModal({
      content: content,
      mask: true,
      showCancel,
      complete: (res) => {
        if (res.cancel) {
          try {
            cancleCallBack()
          } catch (error) {

          }
        }

        if (res.confirm) {
          try {
            okCallBack()
          } catch (error) {

          }
        }
      }
    })
  },
  handleExitLogin() {
    for (let i = 0; i < 100; i++) wx.navigateBack()
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },
  setPageData(_this) {
    _this.setData({
      ...store.getItem('windowInfo'),
      userData: store.getItem('userData'),
      logined: store.getItem('userData') !== undefined,
      isVIP: (store.getItem('userData') !== undefined && store.getItem('userData').isVIP),
      isAdmin: (store.getItem('userData') !== undefined && store.getItem('userData').isAdmin),
      imagePrefix: config.imagePrefix
    })
  },
  controlInput(title = '请输入内容', tip = '请在下面的文本框内输入文字', type = 'singleText', defaultValue = null, callBack = () => { }, check = () => { }) {
    store.setItem('controlInput', {
      title,
      tip,
      type,
      check,
      callBack,
      defaultValue
    })
    wx.navigateTo({
      url: '/pages/inputValue/inputValue',
    })
  },
  controlPicker(title = '请输入内容', tip = '请在下面的文本框内输入文字', type = 'selector', defaultValue = null, options = [], callBack = () => { }, check = () => { }) {
    store.setItem('controlInput', {
      title,
      tip,
      type,
      check,
      callBack,
      defaultValue,
      options
    })
    wx.navigateTo({
      url: '/pages/inputValue/inputValue',
    })
  },
  controlSettingsPage(title = '', optionsOrInit = [], handleToBottom = () => { }) {
    store.setItem('controlSettingsPage', {
      title,
      options: (typeof (optionsOrInit) === 'object' ? optionsOrInit : undefined),
      init: (typeof (optionsOrInit) === 'function' ? optionsOrInit : undefined),
      handleToBottom
    })
    wx.navigateTo({
      url: '/pages/settings/settings',
    })
  },
  async controlSelectLocation(callBack = () => { }) {
    store.setItem('controlSelectLocation', {
      callBack
    })
    let re = await this.requestData('/getCities', {}, 'get')
    if (re.status) {
      let re1 = []
      re = re.data
      for (let i = 0; i < re.length; i++) {
        re1.push({
          title: re[i].provinceName,
          value: re[i].provinceName,
        })
      }
      this.controlPicker('选择省份', '', 'selector', '', re1, (value, done) => {
        let re2 = []
        for (let i = 0; i < re.length; i++) {
          if (re[i].provinceName == value) {
            for (let i1 = 0; i1 < re[i].citys.length; i1++) {
              re2.push({
                title: re[i].citys[i1].cityName,
                value: re[i].citys[i1].cityName
              })
            }
            break
          }
        }
        this.controlPicker('选择市区', '', 'selector', '', re2, async (value2, done2) => {
          try {
            callBack(value, value2)
            wx.navigateBack({
              delta: 2
            })
          } catch (error) {

          }
        }, (value2) => {
          if (!value2) throw new Error('请选择市区')
        })
      }, (value) => {
        if (!value) throw new Error('请选择省份')
      })
    } else {
      this.handleShowToast(re.content, 'error')
    }
  },
  formatTimeNew(inputTime = new Date()) {
    function getPeriod(hours) {
      if (hours >= 0 && hours < 6) {
        return '凌晨';
      } else if (hours >= 6 && hours < 11) {
        return '上午';
      } else if (hours >= 11 && hours < 14) {
        return '中午';
      } else if (hours >= 14 && hours < 18) {
        return '下午';
      } else {
        return '晚上';
      }
    }

    function getWeekName(n) {
      switch (n) {
        case 0:
          return '星期天'
        case 1:
          return '星期一'
        case 2:
          return '星期二'
        case 3:
          return '星期三'
        case 4:
          return '星期四'
        case 5:
          return '星期五'
        case 6:
          return '星期六'
      }
    }
    let currentTime = new Date()
    let oneDaySecond = 86400000
    let currentDayStart = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime
      .getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000)
    let lastDayStart = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime
      .getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000 - oneDaySecond)
    let nextDayStart = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime
      .getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000 + oneDaySecond)
    let nextDayEnd = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime
      .getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000 + oneDaySecond * 2)
    let prefix = ''
    if (inputTime >= currentDayStart && inputTime < nextDayStart) {
      prefix = '今天'
    }
    if (inputTime >= lastDayStart && inputTime < currentDayStart) {
      prefix = '昨天'
    }
    if (inputTime >= nextDayStart && inputTime < nextDayEnd) {
      prefix = '明天'
    }
    if (prefix == '') {
      prefix = (inputTime.getFullYear() == currentTime.getFullYear() ? '' : inputTime.getFullYear().toString() +
        '年') + (inputTime.getMonth() + 1).toString() + '月' + inputTime.getDate() + '日 '
    }
    prefix += getPeriod(inputTime.getHours()) + ' '
    prefix += inputTime.getHours().toString() + ':'
    if (inputTime.getMinutes() < 10) {
      prefix += '0'
    }
    prefix += inputTime.getMinutes().toString() + ' '
    prefix += getWeekName(inputTime.getDay())
    return prefix
  },
  async updateUserDataAndRefreshMain(updateInfo, refreshMain = true) {
    let ttt = store.getItem('userData')
    ttt = Object.assign(ttt, updateInfo)
    store.setItem('userData', ttt)
    if (refreshMain) {
      let mainCurrentPageIndex = store.getItem('mainCurrentPageIndex')
      store.setItem('mainCurrentPageIndex', -1)
      await this.wait(0.1)
      store.setItem('mainCurrentPageIndex', mainCurrentPageIndex)
    }
  },
  compressImage(filePath, quality = 30, maxWidth = 512, maxHeight = 512) {
    return new Promise((resolve, reject) => {
      wx.compressImage({
        src: filePath, // 原始图片路径
        quality: quality, // 压缩质量
        height: maxHeight, // 最大高度
        width: maxWidth, // 最大宽度
        success(res) {
          resolve(res.tempFilePath); // 返回压缩后的图片路径
        },
        fail(err) {
          reject(err); // 如果压缩失败，则返回错误信息
        }
      });
    });
  },
  chooseImage(count = 1) {
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: count, // 选择图片的数量，最多可以选择的数量
        sizeType: ['original', 'compressed'], // 可以选择原图或压缩图
        sourceType: ['album', 'camera'], // 可以选择相册或拍照
        success(res) {
          resolve(res.tempFilePaths); // 返回选择的图片路径数组
        },
        fail(err) {
          reject(err); // 如果选择图片失败，返回错误信息
        }
      });
    });
  },
  dcJSON(obj) {
    return JSON.parse(JSON.stringify(obj))
  },
  async getServerTime() {
    let re = await this.requestData('/getServerTime', {}, 'get')
    if (re.status) {
      return re.data
    } else {
      return undefined
    }
  },
  handleSetAddress() {
    this.controlInput('请输入收货地址', '', 'multipleText', store.getItem('userData').address, async (value, done) => {
      let re = await this.requestData('/user/update/info', {
        openId: store.getItem('userData').openId,
        address: value
      })
      if (re.status) {
        this.updateUserDataAndRefreshMain({
          address: value
        }, false)
        done()
        this.handleShowToast('成功', 'success')
      } else {
        this.handleShowToast(re.content, 'error')
      }
    }, (value) => {

    })
  },
  async getProductList(input = '', sna = false) {
    let re = await this.requestData('/product/getList', { input, sna }, 'get')
    return re
  },
  async getActivityList(input = '', sna = false) {
    let re = await this.requestData('/activity/getList', { input, sna }, 'get')
    return re
  },
  controlAdminManage(title = '', componentName = '', data = {}) {
    store.setItem('controlAdminManage', {
      title,
      componentName,
      data
    })
    wx.navigateTo({
      url: '/pages/adminManage/adminManage',
    })
  },
  async execFunc(func = () => { }, args = []) {
    return await func(...args)
  },
  async handleShowProductEditorPage(productId = undefined) {

    let content_temp = ''

    let item = {
      options: [],
      imageUrl: [],
      soldOut: 0,
      takeOutAvailable: 1,
      isAvailable: 1,
      isVipAvailable: 1,
      isCardAvailable: 1,
      price: 0,
      count: 0,
      title: '新建商品',
      category1: '其他',
      category2: '其他',
    }
    if (productId) {
      let re = await tool.requestData('/product/getSingleInfo', {
        id: productId
      }, 'get')
      if (re.status) {
        item = re.data
      } else {
        tool.handleShowModel(re.content, false, () => {
          wx.navigateBack()
        })
        return []
      }
    }
    tool.controlSettingsPage(`${productId ? '编辑商品' : '新建商品'}`, async (handleReloadProductEditorPage) => {
      async function handleSubmitItemInfoToServer() {
        if (!productId) return
        let re = await tool.requestData('/product/updateInfo', {
          item
        })
        if (re.status) {
          tool.handleShowToast('成功')
        } else {
          tool.handleShowToast(re.content, 'error')
        }
      }
      async function handleAddToServer() {
        if (content_temp) {
          let re = await tool.createTempFile(content_temp)
          re = await tool.uploadFileToServer(re)
          re = JSON.parse(re)
          if (re.status) {
            item.content = re.data
          }
        }

        for (let i = item.imageUrl.length - 1; i >= 0; i--) {
          let re = await tool.uploadFileToServer(item.imageUrl[i])
          re = JSON.parse(re)
          if (re.status) {
            item.imageUrl[i] = re.data
          } else {
            item.imageUrl = [...item.imageUrl.slice(0, i), ...item.imageUrl.slice(i + 1)]
          }
        }
        let re = await tool.requestData('/product/updateInfo', {
          item
        })
        if (re.status) {
          tool.handleShowToast('成功')
        } else {
          tool.handleShowToast(re.content, 'error')
        }
      }
      let re1 = [
        {
          title: '信息',
          list: await tool.execFunc(() => {
            let re = [
              {
                title: '名称',
                right: {
                  type: 'text',
                  value: item.title
                },
                callBack: () => {
                  tool.controlInput('商品名称', '', 'singleText', item.title, async (value, done) => {
                    item.title = value
                    done()
                    handleReloadProductEditorPage()
                    if (productId) await handleSubmitItemInfoToServer()
                  }, (value) => {
                    if (!value) throw new Error('商品名称不能为空')
                  })
                }
              },
              {
                title: '副标题',
                right: {
                  type: 'text',
                  value: item.subTitle
                },
                callBack: () => {
                  tool.controlInput('商品副标题', '', 'multipleText', item.subTitle, async (value, done) => {
                    item.subTitle = value
                    done()
                    handleReloadProductEditorPage()
                    if (productId) await handleSubmitItemInfoToServer()
                  }, (value) => {

                  })
                }
              },
              {
                title: '价格',
                right: {
                  type: 'text',
                  value: item.price / 100
                },
                callBack: () => {
                  tool.controlInput('商品价格（分）', '', 'number', item.price, async (value, done) => {
                    value = parseInt(value)
                    item.price = value
                    done()
                    handleReloadProductEditorPage()
                    if (productId) await handleSubmitItemInfoToServer()
                  }, (value) => {
                    if (isNaN(value)) throw new Error('商品价格应为非负整数')
                    if (value < 0) throw new Error('商品价格应为非负整数')
                  })
                }
              },
              {
                title: '类别',
                right: {
                  type: 'text',
                  value: item.category1
                },
                callBack: () => {
                  wx.showActionSheet({
                    itemList: ['输入类别', '选择已有类别'],
                    success: async (e) => {
                      e = e.tapIndex
                      if (!e) {
                        tool.controlInput('商品类别', '', 'singleText', item.category1, async (value, done) => {
                          item.category1 = value
                          done()
                          handleReloadProductEditorPage()
                          if (productId) await handleSubmitItemInfoToServer()
                        }, (value) => {
                          if (!value) throw new Error('请输入商品类别')
                        })
                      } else {
                        let re = await tool.getProductCategoryList()
                        if (re) {
                          let list = []
                          for (let i = 0; i < re.length; i++)list.push({
                            title: re[i].title,
                            value: re[i].title
                          })
                          tool.controlPicker('商品类别', '', 'selector', item.category1, list, async (value, done) => {
                            item.category1 = value
                            done()
                            handleReloadProductEditorPage()
                            if (productId) await handleSubmitItemInfoToServer()
                          }, (value) => {
                            if (!value) throw new Error('请选择商品类别')
                          })
                        }
                      }
                    }
                  })
                }
              },
              {
                title: '子类别',
                right: {
                  type: 'text',
                  value: item.category2
                },
                callBack: async () => {
                  let ol = ['输入子类别', '选择已有子类别']
                  let re = await tool.getProductCategoryList()
                  if (re) {
                    let list2 = []
                    for (let i = 0; i < re.length; i++) {
                      if (re[i].title == item.category1) {
                        for (let i1 = 0; i1 < re[i].children.length; i1++) {
                          list2.push({
                            title: re[i].children[i1].title,
                            value: re[i].children[i1].title,
                          })
                        }
                      }
                      break
                    }
                    if (!list2.length) {
                      ol = [ol[0]]
                    }
                    wx.showActionSheet({
                      itemList: ol,
                      success: async (e) => {
                        e = e.tapIndex
                        if (!e) {
                          tool.controlInput('商品子类别', '', 'singleText', item.category2, async (value, done) => {
                            item.category2 = value
                            done()
                            handleReloadProductEditorPage()
                            if (productId) await handleSubmitItemInfoToServer()
                          }, (value) => {
                            if (!value) throw new Error('请输入商品子类别')
                          })
                        } else {
                          tool.controlPicker('商品子类别', '', 'selector', item.category2, list2, async (value, done) => {
                            item.category2 = value
                            done()
                            handleReloadProductEditorPage()
                            if (productId) await handleSubmitItemInfoToServer()
                          }, (value) => {
                            if (!value) throw new Error('请选择商品子类别')
                          })
                        }
                      }
                    })
                  } else {
                    tool.handleShowToast(re.content, 'error')
                  }

                }
              },
              {
                title: '库存数量',
                right: {
                  type: 'text',
                  value: item.count
                },
                callBack: () => {
                  tool.controlInput('商品库存数量', '', 'number', item.count, async (value, done) => {
                    item.count = parseInt(value)
                    done()
                    handleReloadProductEditorPage()
                    if (productId) await handleSubmitItemInfoToServer()
                  }, (value) => {
                    if (isNaN(value)) throw new Error('商品库存数量应为非负整数')
                    if (value < 0) throw new Error('商品库存数量应为非负整数')
                  })
                }
              },
              {
                title: '介绍',
                callBack: async () => {
                  let content = ''
                  if (productId) {
                    let re = await tool.requestData('/getTextFileContent', {
                      fileName: item.content
                    }, 'get')
                    if (re.status) content = re.data
                  }

                  tool.controlRichTextEditor('编辑商品介绍', content, async (value) => {
                    try {
                      if (value != content) {
                        if (!productId) {
                          content_temp = value
                          wx.navigateBack()
                          return
                        }
                        await tool.requestData('/file/delete', {
                          fileName: item.content
                        })
                        if (value) {
                          let re = await tool.createTempFile(value)
                          re = await tool.uploadFileToServer(re)
                          re = JSON.parse(re)
                          if (re.status) {
                            item.content = re.data
                            await handleSubmitItemInfoToServer()
                            wx.navigateBack()
                          } else {
                            tool.handleShowToast(re.content)
                          }
                        } else {
                          item.content = ''
                          await handleSubmitItemInfoToServer()
                          wx.navigateBack()
                        }
                      } else {
                        wx.navigateBack()
                      }
                    } catch (error) {

                    }

                  })
                }
              },

            ]

            return re
          })
        },
        ...(await tool.execFunc(() => {
          return [
            {
              title: '权限',
              list: [
                {
                  title: '允许购买',
                  right: {
                    type: 'switch',
                    value: item.isAvailable
                  },
                  callBack: async (x, value) => {
                    item.isAvailable = value ? 1 : 0
                    await handleSubmitItemInfoToServer()
                    handleReloadProductEditorPage()
                  }
                },
                // {
                //   title: '允许会员优惠',
                //   right: {
                //     type: 'switch',
                //     value: item.isVipAvailable
                //   },
                //   callBack: async (x, value) => {
                //     item.isVipAvailable = value ? 1 : 0
                //     await handleSubmitItemInfoToServer()
                //     handleReloadProductEditorPage()
                //   }
                // },
                // {
                //   title: '允许优惠券优惠',
                //   right: {
                //     type: 'switch',
                //     value: item.isCardAvailable
                //   },
                //   callBack: async (x, value) => {
                //     item.isCardAvailable = value ? 1 : 0
                //     await handleSubmitItemInfoToServer()
                //     handleReloadProductEditorPage()
                //   }
                // },
                {
                  title: '允许寄送',
                  right: {
                    type: 'switch',
                    value: item.takeOutAvailable
                  },
                  callBack: async (x, value) => {
                    item.takeOutAvailable = value ? 1 : 0
                    await handleSubmitItemInfoToServer()
                    handleReloadProductEditorPage()
                  }
                },
              ]
            }
          ]
        }))
        ,
        ...(await tool.execFunc(() => {

          let re = []
          for (let i = 0; i < item.imageUrl.length; i++) {
            re.push({
              title: `图片${i + 1}`,
              right: {
                type: productId ? 'image' : 'webImage',
                src: item.imageUrl[i]
              },
              callBack: async () => {
                let ol = ['设为封面图', '预览']
                if (i) ol.push('上移')
                if (i < item.imageUrl.length - 1) ol.push('下移')
                ol.push('删除')
                wx.showActionSheet({
                  itemList: ol,
                  success: async (e) => {
                    e = e.tapIndex
                    switch (ol[e]) {
                      case '设为封面图':
                        {
                          let t = item.imageUrl[i]
                          item.imageUrl = [...item.imageUrl.slice(0, i), ...item.imageUrl.slice(i + 1)]
                          item.imageUrl = [t, ...item.imageUrl]
                          await handleSubmitItemInfoToServer()
                          handleReloadProductEditorPage()
                        }
                        break;
                      case '预览':
                        {
                          let re = []
                          for (let i1 = 0; i1 < item.imageUrl.length; i1++) {
                            re.push((productId ? config.imagePrefix : '') + item.imageUrl[i1])
                          }
                          wx.previewImage({
                            urls: re,
                            current: (productId ? config.imagePrefix : '') + item.imageUrl[i]
                          })
                        }
                        break;
                      case '上移':
                        {
                          let t = item.imageUrl[i]
                          item.imageUrl[i] = item.imageUrl[i - 1]
                          item.imageUrl[i - 1] = t
                          await handleSubmitItemInfoToServer()
                          handleReloadProductEditorPage()
                        }
                        break;
                      case '下移':
                        {
                          let t = item.imageUrl[i]
                          item.imageUrl[i] = item.imageUrl[i + 1]
                          item.imageUrl[i + 1] = t
                          await handleSubmitItemInfoToServer()
                          handleReloadProductEditorPage()
                        }
                        break;
                      case '删除':
                        if (!productId) {
                          item.imageUrl = [...item.imageUrl.slice(0, i), ...item.imageUrl.slice(i + 1)]
                          handleReloadProductEditorPage()
                          return
                        }
                        {
                          tool.handleShowModel('是否删除此图片？', true, async () => {
                            let t = item.imageUrl[i]
                            item.imageUrl = [...item.imageUrl.slice(0, i), ...item.imageUrl.slice(i + 1)]
                            let re = await tool.requestData('/file/delete', {
                              fileName: t
                            })
                            if (re.status) {
                              await handleSubmitItemInfoToServer()
                            } else {
                              tool.handleShowToast(re.content, 'error')
                            }
                            handleReloadProductEditorPage()
                          })
                        }
                        break;
                    }
                  }
                })
              }
            })
          }

          if (item.imageUrl.length < 9) {
            re.push({
              title: '添加',
              icon: 'add',
              callBack: async () => {
                if (!productId) {
                  let re = await tool.chooseImage(1)
                  if (re.length) {
                    re = re[0]
                    re = await tool.compressImage(re)
                    item.imageUrl.push(re)
                  }
                  handleReloadProductEditorPage()
                  return
                }
                try {
                  let re = await tool.chooseImage(1)
                  if (re.length) {
                    re = re[0]
                    re = await tool.compressImage(re)
                    re = await tool.uploadFileToServer(re)
                    re = JSON.parse(re)
                    if (re.status) {
                      item.imageUrl.push(re.data)
                      await handleSubmitItemInfoToServer()
                      handleReloadProductEditorPage()
                      console.log(item)
                    } else {
                      tool.handleShowToast(re.content, 'error')
                    }
                  }
                } catch (error) {
                  console.log(error)
                }

              }
            })
          }

          return [{
            title: '图片',
            list: re
          }]
        }))
        ,
        {
          title: '选项',
          list: await tool.execFunc(async () => {
            let re = []
            for (let i = 0; i < item.options.length; i++) {
              re.push({
                title: `${item.options[i].title}`,
                right: {
                  type: 'text',
                  value: `${item.options[i].items.length}个子选项`
                },
                callBack: async () => {
                  let l = ['修改', '编辑子选项', '删除']
                  if (item.options[i].required) {
                    l.push('设为非必选项')
                  } else {
                    l.push('设为必选项')
                  }
                  wx.showActionSheet({
                    itemList: l,
                    success: async (e) => {
                      e = e.tapIndex
                      if (e == 0) {
                        tool.controlInput('请输入选项内容', '', 'singleText', item.options[i].title, async (value, done) => {
                          item.options[i].title = value
                          await handleSubmitItemInfoToServer()
                          handleReloadProductEditorPage()
                          done()
                        }, (value) => {
                          if (!value) throw new Error('请输入选项内容')
                          for (let i = 0; i < item.options.length; i++) {
                            if (item.options[i].title == value) {
                              throw new Error('和已有的选项重复或未改动')
                            }
                          }
                        })
                      }
                      if (e == 1) {
                        tool.controlSettingsPage(`编辑${item.options[i].title}的子选项`, async (handleReloadSubOptionsPage) => {

                          let re = [
                            {
                              list: await tool.execFunc(async () => {
                                let re = []
                                for (let i1 = 0; i1 < item.options[i].items.length; i1++) {
                                  re.push({
                                    title: item.options[i].items[i1],
                                    right: {
                                      type: 'text',
                                      value: `变动${item.options[i].prices[i1]}`
                                    },
                                    callBack: async () => {
                                      try {
                                        let ol = ['修改内容', '修改价格变动']
                                        if (i1) ol.push('上移')
                                        if (i1 < item.options[i].items.length - 1) ol.push('下移')
                                        ol.push('删除')
                                        wx.showActionSheet({
                                          itemList: ol,
                                          fail(e) {
                                            console.log(e)
                                          },
                                          success: async (e) => {
                                            e = e.tapIndex
                                            switch (ol[e]) {
                                              case '修改内容':
                                                tool.controlInput('修改子选项内容', '', 'singleText', item.options[i].items[i1], async (value, done) => {
                                                  item.options[i].items[i1] = value
                                                  await handleSubmitItemInfoToServer()
                                                  handleReloadSubOptionsPage()
                                                  done()
                                                }, (value) => {
                                                  if (!value) throw new Error('请输入子选项')
                                                  if ((item.options[i].items.indexOf(value) + 1)) {
                                                    throw new Error('与其他子选项重复或未改动')
                                                  }
                                                })
                                                break;
                                              case '修改价格变动':
                                                tool.controlInput('修改子选项价格变动', '', 'number', item.options[i].prices[i1], async (value, done) => {
                                                  item.options[i].prices[i1] = parseInt(value)
                                                  await handleSubmitItemInfoToServer()
                                                  handleReloadSubOptionsPage()
                                                  done()
                                                }, (value) => {
                                                  if (isNaN(parseInt(value))) throw '应为整数'
                                                })
                                                break;
                                              case '上移':
                                                {
                                                  {
                                                    let t = item.options[i].items[i1]
                                                    item.options[i].items[i1] = item.options[i].items[i1 - 1]
                                                    item.options[i].items[i1 - 1] = t
                                                  }
                                                  {
                                                    let t = item.options[i].prices[i1]
                                                    item.options[i].prices[i1] = item.options[i].prices[i1 - 1]
                                                    item.options[i].prices[i1 - 1] = t
                                                  }
                                                  await handleSubmitItemInfoToServer()
                                                  handleReloadSubOptionsPage()
                                                }
                                                break;
                                              case '下移':
                                                {
                                                  {
                                                    let t = item.options[i].items[i1]
                                                    item.options[i].items[i1] = item.options[i].items[i1 + 1]
                                                    item.options[i].items[i1 + 1] = t
                                                  }
                                                  {
                                                    let t = item.options[i].prices[i1]
                                                    item.options[i].prices[i1] = item.options[i].prices[i1 + 1]
                                                    item.options[i].prices[i1 + 1] = t
                                                  }
                                                  await handleSubmitItemInfoToServer()
                                                  handleReloadSubOptionsPage()
                                                }
                                                break;
                                              case '删除':
                                                {
                                                  item.options[i].items = [...item.options[i].items.slice(0, i1), ...item.options[i].items.slice(i1 + 1)]
                                                  item.options[i].prices = [...item.options[i].prices.slice(0, i1), ...item.options[i].prices.slice(i1 + 1)]
                                                  await handleSubmitItemInfoToServer()
                                                  handleReloadSubOptionsPage()
                                                  handleReloadProductEditorPage()
                                                }
                                                break;
                                            }
                                          }
                                        })
                                      } catch (error) {
                                        console.log(error)
                                      }
                                    }
                                  })
                                }
                                return re
                              })
                            },
                            {
                              title: '操作',
                              list: [
                                {
                                  title: '添加',
                                  icon: 'add',
                                  callBack: async () => {
                                    tool.controlInput('请输入子选项', '', 'singleText', '', async (value, done) => {
                                      item.options[i].items.push(value)
                                      item.options[i].prices.push(0)
                                      await handleSubmitItemInfoToServer()
                                      handleReloadSubOptionsPage()
                                      handleReloadProductEditorPage()
                                      done()
                                    }, (value) => {
                                      if (!value) throw new Error('请输入子选项内容')
                                      if ((item.options[i].items.indexOf(value) + 1)) {
                                        throw new Error('与其他子选项重复')
                                      }
                                    })
                                  }
                                }
                              ]
                            }
                          ]

                          return re
                        })
                      }
                      if (e == 2) {
                        tool.handleShowModel('是否删除此选项？', true, async () => {
                          item.options = [...item.options.slice(0, i), ...item.options.slice(i + 1)]
                          await handleSubmitItemInfoToServer()
                          handleReloadProductEditorPage()
                        })
                      }
                      if (e == 3) {
                        item.options[i].required = !item.options[i].required
                        await handleSubmitItemInfoToServer()
                        handleReloadProductEditorPage()
                      }
                    }
                  })
                }
              })
            }

            re.push({
              title: '添加',
              icon: 'add',
              callBack: async () => {
                tool.controlInput('请输入选项内容', '', 'singleText', '', async (value, done) => {
                  item.options.push({
                    title: value,
                    items: [],
                    prices: []
                  })
                  await handleSubmitItemInfoToServer()
                  handleReloadProductEditorPage()
                  done()
                }, (value) => {
                  if (!value) {
                    throw new Error('请输入选项内容')
                  }
                  for (let i = 0; i < item.options.length; i++) {
                    if (item.options[i].title == value) {
                      throw new Error('和已有的选项重复')
                    }
                  }
                })
              }
            })

            return re
          })
        }
        ,
        ...(await tool.execFunc(() => {
          if (productId) return [{
            title: '操作',
            list: [
              {
                title: '生成二维码',
                icon: 'add',
                callBack: async () => {
                  // qrcodeg
                  tool.flow(async () => {
                    let re = await tool.getQRCode(`pages/index/index?type=share&isPro=${item.isPro ? true : false}&id=${item.id}`)
                    wx.previewImage({
                      urls: [re],
                    })
                  }, err => tool.handleShowToast(`${err}`, 'error'))
                }
              },
              {
                title: `删除当前商品`,
                icon: 'delete',
                callBack: async () => {
                  tool.handleShowModel('是否删除当前商品？', true, async () => {
                    let re = await tool.requestData('/product/delete', {
                      id: productId
                    })
                    if (re.status) {
                      tool.handleShowToast('成功', 'success')
                      wx.navigateBack()
                    } else {
                      tool.handleShowToast(re.content)
                    }
                  })
                }
              }
            ]
          }]
          return [{
            title: '操作',
            list: [
              {
                title: `${productId ? '保存更改' : '保存商品信息'}`,
                icon: '保存',
                callBack: async () => {
                  await handleAddToServer()
                  wx.navigateBack()
                }
              }
            ]
          }]
        }))
      ]

      if (productId) {
        re1 = [
          {
            list: [
              {
                title: 'ID',
                right: {
                  type: 'text',
                  value: item.id
                },
                disabled: true
              },
              {
                title: '已售',
                right: {
                  type: 'text',
                  value: item.soldOut
                },
                disabled: true
              },
              {
                title: '创建时间',
                right: {
                  type: 'text',
                  value: tool.formatTimeNew(new Date(item.createdAt))
                },
                disabled: true
              },
              {
                title: '更新时间',
                right: {
                  type: 'text',
                  value: tool.formatTimeNew(new Date(item.updatedAt))
                },
                disabled: true
              },
            ]
          },
          ...re1
        ]
      }

      return re1
    })
  },
  async getProductCategoryList() {
    let re = await tool.requestData('/product/getList', {}, 'get')
    if (re.status) {
      return re.data
    } else {
      return undefined
    }
  },
  async getActivityCategoryList() {
    let re = await tool.requestData('/activity/getList', {}, 'get')
    if (re.status) {
      return re.data
    } else {
      return undefined
    }
  },
  async handleShowActivityEditorPage(activityId = undefined) {
    let item = {
      title: "新建活动",
      subTitle: "",
      content: "",
      price: 0,
      category1: "其他",
      category2: "其他",
      imageUrl: [],
      startRegistration: tool.formatDateTime(new Date((new Date()).getTime())),
      endRegistration: tool.formatDateTime(new Date((new Date()).getTime() + 1000 * 60 * 60)),
      startTime: tool.formatDateTime(new Date((new Date()).getTime() + 1000 * 60 * 60 * 2)),
      endTime: tool.formatDateTime(new Date((new Date()).getTime() + 1000 * 60 * 60 * 3)),
      maxParticipants: 0,
      location: "未知",
      joinedUserCount: 0,
      options: []
    }
    let content_temp = ''
    if (activityId) {
      let re = await tool.requestData('/activity/getSingleInfo', {
        id: activityId
      }, 'get')
      if (re.status) {
        item = re.data
      } else {
        tool.handleShowModel(re.content, false, () => {
          wx.navigateBack()
        })
        return []
      }
    }
    tool.controlSettingsPage(`${activityId ? '编辑活动' : '新建活动'}`, async (handleReloadActivityEditorPage) => {
      async function handleSubmitItemInfoToServer() {
        if (!activityId) return
        let re = await tool.requestData('/activity/updateInfo', {
          item
        })
        if (re.status) {
          tool.handleShowToast('成功')
        } else {
          tool.handleShowToast(re.content, 'error')
        }
      }
      async function handleAddToServer() {


        if (content_temp) {
          let re = await tool.createTempFile(content_temp)
          re = await tool.uploadFileToServer(re)
          re = JSON.parse(re)
          if (re.status) {
            item.content = re.data
          }
        }

        for (let i = item.imageUrl.length - 1; i >= 0; i--) {
          let re = await tool.uploadFileToServer(item.imageUrl[i])
          re = JSON.parse(re)
          if (re.status) {
            item.imageUrl[i] = re.data
          } else {
            item.imageUrl = [...item.imageUrl.slice(0, i), ...item.imageUrl.slice(i + 1)]
          }
        }
        let re = await tool.requestData('/activity/updateInfo', {
          item
        })
        if (re.status) {
          tool.handleShowToast('成功')
        } else {
          tool.handleShowToast(re.content, 'error')
        }
      }
      let re1 = [
        {
          title: '信息',
          list: await tool.execFunc(() => {
            let re = [
              {
                title: '名称',
                right: {
                  type: 'text',
                  value: item.title
                },
                callBack: () => {
                  tool.controlInput('活动名称', '', 'singleText', item.title, async (value, done) => {
                    item.title = value
                    done()
                    handleReloadActivityEditorPage()
                    if (activityId) await handleSubmitItemInfoToServer()
                  }, (value) => {
                    if (!value) throw new Error('活动名称不能为空')
                  })
                }
              },
              {
                title: '副标题',
                right: {
                  type: 'text',
                  value: item.subTitle
                },
                callBack: () => {
                  tool.controlInput('活动副标题', '', 'multipleText', item.subTitle, async (value, done) => {
                    item.subTitle = value
                    done()
                    handleReloadActivityEditorPage()
                    if (activityId) await handleSubmitItemInfoToServer()
                  }, (value) => {

                  })
                }
              },
              {
                title: '价格',
                right: {
                  type: 'text',
                  value: item.price / 100
                },
                callBack: () => {
                  tool.controlInput('活动价格（分）', '', 'number', item.price, async (value, done) => {
                    value = parseInt(value)
                    item.price = value
                    done()
                    handleReloadActivityEditorPage()
                    if (activityId) await handleSubmitItemInfoToServer()
                  }, (value) => {
                    if (isNaN(value)) throw new Error('活动价格应为非负整数')
                    if (value < 0) throw new Error('活动价格应为非负整数')
                  })
                }
              },
              {
                title: '类别',
                right: {
                  type: 'text',
                  value: item.category1
                },
                callBack: () => {
                  wx.showActionSheet({
                    itemList: ['输入类别', '选择已有类别'],
                    success: async (e) => {
                      e = e.tapIndex
                      if (!e) {
                        tool.controlInput('活动类别', '', 'singleText', item.category1, async (value, done) => {
                          item.category1 = value
                          done()
                          handleReloadActivityEditorPage()
                          if (activityId) await handleSubmitItemInfoToServer()
                        }, (value) => {
                          if (!value) throw new Error('请输入活动类别')
                        })
                      } else {
                        let re = await tool.getActivityCategoryList()
                        if (re) {
                          let list = []
                          for (let i = 0; i < re.length; i++)list.push({
                            title: re[i].title,
                            value: re[i].title
                          })
                          tool.controlPicker('活动类别', '', 'selector', item.category1, list, async (value, done) => {
                            item.category1 = value
                            done()
                            handleReloadActivityEditorPage()
                            if (activityId) await handleSubmitItemInfoToServer()
                          }, (value) => {
                            if (!value) throw new Error('请选择活动类别')
                          })
                        }
                      }
                    }
                  })
                }
              },
              {
                title: '子类别',
                right: {
                  type: 'text',
                  value: item.category2
                },
                callBack: async () => {
                  let ol = ['输入子类别', '选择已有子类别']
                  let re = await tool.getActivityCategoryList()
                  if (re) {
                    let list2 = []
                    for (let i = 0; i < re.length; i++) {
                      if (re[i].title == item.category1) {
                        for (let i1 = 0; i1 < re[i].children.length; i1++) {
                          list2.push({
                            title: re[i].children[i1].title,
                            value: re[i].children[i1].title,
                          })
                        }
                      }
                      break
                    }
                    if (!list2.length) {
                      ol = [ol[0]]
                    }
                    wx.showActionSheet({
                      itemList: ol,
                      success: async (e) => {
                        e = e.tapIndex
                        if (!e) {
                          tool.controlInput('活动子类别', '', 'singleText', item.category2, async (value, done) => {
                            item.category2 = value
                            done()
                            handleReloadActivityEditorPage()
                            if (activityId) await handleSubmitItemInfoToServer()
                          }, (value) => {
                            if (!value) throw new Error('请输入活动子类别')
                          })
                        } else {
                          tool.controlPicker('活动子类别', '', 'selector', item.category2, list2, async (value, done) => {
                            item.category2 = value
                            done()
                            handleReloadActivityEditorPage()
                            if (activityId) await handleSubmitItemInfoToServer()
                          }, (value) => {
                            if (!value) throw new Error('请选择活动子类别')
                          })
                        }
                      }
                    })
                  } else {
                    tool.handleShowToast(re.content, 'error')
                  }

                }
              },
              {
                title: '最大参与人数',
                right: {
                  type: 'text',
                  value: item.maxParticipants
                },
                callBack: () => {
                  tool.controlInput('活动最大参与人数', '', 'number', item.maxParticipants, async (value, done) => {
                    item.maxParticipants = parseInt(value)
                    done()
                    handleReloadActivityEditorPage()
                    if (activityId) await handleSubmitItemInfoToServer()
                  }, (value) => {
                    if (isNaN(value)) throw new Error('活动最大参与人数应为非负整数')
                    if (value < 0) throw new Error('活动最大参与人数应为非负整数')
                    if (activityId) {
                      if (value < item.joinedUserCount) {
                        throw new Error('活动最大参与人数应不小于已参加人数')
                      }
                    }
                  })
                }
              },
              {
                title: '地点',
                right: {
                  type: 'text',
                  value: item.location
                },
                callBack: () => {
                  tool.controlInput('活动地点', '', 'singleText', item.location, async (value, done) => {
                    item.location = value
                    done()
                    handleReloadActivityEditorPage()
                    if (activityId) await handleSubmitItemInfoToServer()
                  }, (value) => {
                    if (!value) throw new Error('活动地点不能为空')
                  })
                }
              },
              {
                title: '介绍',
                callBack: async () => {
                  let content = ''
                  if (activityId) {
                    let re = await tool.requestData('/getTextFileContent', {
                      fileName: item.content
                    }, 'get')
                    if (re.status) content = re.data
                  }

                  tool.controlRichTextEditor('编辑活动介绍', content, async (value) => {
                    try {
                      if (value != content) {
                        if (!activityId) {
                          content_temp = value
                          wx.navigateBack()
                          return
                        }
                        await tool.requestData('/file/delete', {
                          fileName: item.content
                        })
                        if (value) {
                          let re = await tool.createTempFile(value)
                          re = await tool.uploadFileToServer(re)
                          re = JSON.parse(re)
                          if (re.status) {
                            item.content = re.data
                            await handleSubmitItemInfoToServer()
                            wx.navigateBack()
                          } else {
                            tool.handleShowToast(re.content)
                          }
                        } else {
                          item.content = ''
                          await handleSubmitItemInfoToServer()
                          wx.navigateBack()
                        }

                      } else {
                        wx.navigateBack()
                      }
                    } catch (error) {

                    }

                  })
                }
              },
            ]

            return re
          })
        },
        ...(await tool.execFunc(() => {

          let re = []
          for (let i = 0; i < item.imageUrl.length; i++) {
            re.push({
              title: `图片${i + 1}`,
              right: {
                type: activityId ? 'image' : 'webImage',
                src: item.imageUrl[i]
              },
              callBack: async () => {
                let ol = ['设为封面图', '预览']
                if (i) ol.push('上移')
                if (i < item.imageUrl.length - 1) ol.push('下移')
                ol.push('删除')
                wx.showActionSheet({
                  itemList: ol,
                  success: async (e) => {
                    e = e.tapIndex
                    switch (ol[e]) {
                      case '设为封面图':
                        {
                          let t = item.imageUrl[i]
                          item.imageUrl = [...item.imageUrl.slice(0, i), ...item.imageUrl.slice(i + 1)]
                          item.imageUrl = [t, ...item.imageUrl]
                          await handleSubmitItemInfoToServer()
                          handleReloadActivityEditorPage()
                        }
                        break;
                      case '预览':
                        {
                          let re = []
                          for (let i1 = 0; i1 < item.imageUrl.length; i1++) {
                            re.push((activityId ? config.imagePrefix : '') + item.imageUrl[i1])
                          }
                          wx.previewImage({
                            urls: re,
                            current: (activityId ? config.imagePrefix : '') + item.imageUrl[i]
                          })
                        }
                        break;
                      case '上移':
                        {
                          let t = item.imageUrl[i]
                          item.imageUrl[i] = item.imageUrl[i - 1]
                          item.imageUrl[i - 1] = t
                          await handleSubmitItemInfoToServer()
                          handleReloadActivityEditorPage()
                        }
                        break;
                      case '下移':
                        {
                          let t = item.imageUrl[i]
                          item.imageUrl[i] = item.imageUrl[i + 1]
                          item.imageUrl[i + 1] = t
                          await handleSubmitItemInfoToServer()
                          handleReloadActivityEditorPage()
                        }
                        break;
                      case '删除':
                        if (!activityId) {
                          item.imageUrl = [...item.imageUrl.slice(0, i), ...item.imageUrl.slice(i + 1)]
                          handleReloadActivityEditorPage()
                          return
                        }
                        {
                          tool.handleShowModel('是否删除此图片？', true, async () => {
                            let t = item.imageUrl[i]
                            item.imageUrl = [...item.imageUrl.slice(0, i), ...item.imageUrl.slice(i + 1)]
                            let re = await tool.requestData('/file/delete', {
                              fileName: t
                            })
                            if (re.status) {
                              await handleSubmitItemInfoToServer()
                            } else {
                              tool.handleShowToast(re.content, 'error')
                            }
                            handleReloadActivityEditorPage()
                          })
                        }
                        break;
                    }
                  }
                })
              }
            })
          }

          if (item.imageUrl.length < 9) {
            re.push({
              title: '添加',
              icon: 'add',
              callBack: async () => {
                if (!activityId) {
                  let re = await tool.chooseImage(1)
                  if (re.length) {
                    re = re[0]
                    re = await tool.compressImage(re)
                    item.imageUrl.push(re)
                  }
                  handleReloadActivityEditorPage()
                  return
                }
                try {
                  let re = await tool.chooseImage(1)
                  if (re.length) {
                    re = re[0]
                    re = await tool.compressImage(re)
                    re = await tool.uploadFileToServer(re)
                    re = JSON.parse(re)
                    if (re.status) {
                      item.imageUrl.push(re.data)
                      await handleSubmitItemInfoToServer()
                      handleReloadActivityEditorPage()
                      console.log(item)
                    } else {
                      tool.handleShowToast(re.content, 'error')
                    }
                  }
                } catch (error) {
                  console.log(error)
                }

              }
            })
          }

          return [{
            title: '图片',
            list: re
          }]
        }))
        ,
        {
          title: '时间',
          list: [
            {
              title: '报名开始时间',
              right: {
                type: 'text',
                value: tool.formatDateTime(item.startRegistration)
              },
              callBack: async () => {
                tool.controlInput('选择活动报名开始时间', '', 'dateTime', tool.formatDateTime(item.startRegistration), async (value, done) => {
                  item.startRegistration = value
                  done()
                  await handleSubmitItemInfoToServer()
                  handleReloadActivityEditorPage()
                }, (value) => {
                  if (new Date(value) >= new Date(item.endRegistration)) {
                    throw new Error('报名开始时间应早于报名结束时间')
                  }
                })
              }
            },
            {
              title: '报名结束时间',
              right: {
                type: 'text',
                value: tool.formatDateTime(item.endRegistration)
              },
              callBack: async () => {
                tool.controlInput('选择活动报名结束时间', '', 'dateTime', tool.formatDateTime(item.endRegistration), async (value, done) => {
                  item.endRegistration = value
                  done()
                  await handleSubmitItemInfoToServer()
                  handleReloadActivityEditorPage()
                }, (value) => {
                  if (new Date(value) <= new Date(item.startRegistration)) {
                    throw new Error('报结束时间应晚于报名开始时间')
                  }
                  if (new Date(value) >= new Date(item.startTime)) {
                    throw new Error('报名结束时间应早于活动开始时间')
                  }
                })
              }
            },
            {
              title: '活动开始时间',
              right: {
                type: 'text',
                value: tool.formatDateTime(item.startTime)
              },
              callBack: async () => {
                tool.controlInput('选择活动活动开始时间', '', 'dateTime', tool.formatDateTime(item.startTime), async (value, done) => {
                  item.startTime = value
                  done()
                  await handleSubmitItemInfoToServer()
                  handleReloadActivityEditorPage()
                }, (value) => {
                  if (new Date(value) >= new Date(item.endTime)) {
                    throw new Error('活动开始时间应早于活动结束时间')
                  }
                  if (new Date(value) <= new Date(item.endRegistration)) {
                    throw new Error('活动开始时间应晚于报名时间')
                  }
                })
              }
            },
            {
              title: '活动结束时间',
              right: {
                type: 'text',
                value: tool.formatDateTime(item.endTime)
              },
              callBack: async () => {
                tool.controlInput('选择活动活动结束时间', '', 'dateTime', tool.formatDateTime(item.endTime), async (value, done) => {
                  item.endTime = value
                  done()
                  await handleSubmitItemInfoToServer()
                  handleReloadActivityEditorPage()
                  if (new Date(value) <= new Date(item.startTime)) {
                    throw new Error('报结束时间应晚于活动开始时间')
                  }
                })
              }
            },
          ]
        },
        {
          title: '表单',
          list: await tool.execFunc(async () => {
            if (!(item.options instanceof Array)) item.options = []
            let re = []
            for (let i = 0; i < item.options.length; i++) {
              re.push({
                title: item.options[i].title,
                right: {
                  type: 'text',
                  value: `${item.options[i].type}${item.options[i].required ? `（必${item.options[i].type == '文本' ? '填' : '选'}）` : ''}`
                },
                callBack: async () => {
                  let ls = ['删除', '修改', `设为${item.options[i].required ? '非' : ''}必选项`]
                  wx.showActionSheet({
                    itemList: ls,
                    success: async (e) => {
                      e = e.tapIndex
                      if (e === 0) {
                        tool.handleShowModel('删除此字段？', true, async () => {
                          item.options = [...item.options.slice(0, i), ...item.options.slice(i + 1)]
                          await handleSubmitItemInfoToServer()
                          handleReloadActivityEditorPage()
                        })
                      }
                      if (e === 1) {
                        tool.controlSettingsPage(`编辑字段`, async (reloadEditFieldPage) => {
                          return [
                            {
                              list: [
                                {
                                  title: '类型',
                                  right: {
                                    type: 'text',
                                    value: item.options[i].type
                                  }
                                },
                                ...await tool.execFunc(async () => {
                                  if (item.options[i].type == '文本') {
                                    return [
                                      {
                                        title: '长度限制',
                                        right: {
                                          type: 'text',
                                          value: item.options[i].limit
                                        },
                                        callBack: async () => {
                                          tool.controlInput('编辑字段长度限制', '', 'number', item.options[i].limit, async (value, done) => {
                                            item.options[i].limit = value
                                            await handleSubmitItemInfoToServer()
                                            handleReloadActivityEditorPage()
                                            reloadEditFieldPage()
                                            done()
                                          }, (value) => {
                                            value = parseInt(value)
                                            if (isNaN(value)) throw '应为正整数'
                                            if (value < 1) throw '应为正整数'
                                          })
                                        }
                                      }
                                    ]
                                  }
                                  if (item.options[i].type == '选项') {
                                    return [
                                      {
                                        title: '编辑选项',
                                        right: {
                                          type: 'text',
                                          value: item.options[i].options.length
                                        },
                                        callBack: async () => {
                                          tool.controlSettingsPage('编辑字段选项', async (reloadEditFieldOptionsPage) => {
                                            let re = []
                                            for (let i1 = 0; i1 < item.options[i].options.length; i1++) {
                                              re.push({
                                                title: item.options[i].options[i1],
                                                callBack: async () => {
                                                  let ls = ['修改', '删除',
                                                    ...await tool.execFunc(async () => {
                                                      let t = []
                                                      if (i1 > 0) t.push('上移')
                                                      if (i1 < item.options[i].options.length - 1) t.push('下移')
                                                      return t
                                                    })
                                                  ]
                                                  wx.showActionSheet({
                                                    itemList: ls,
                                                    success: async (e) => {
                                                      e = e.tapIndex
                                                      let selected = ls[e]
                                                      if (selected == '上移') {
                                                        let t = item.options[i].options[i1]
                                                        item.options[i].options[i1] = item.options[i].options[i1 - 1]
                                                        item.options[i].options[i1 - 1] = t
                                                        await handleSubmitItemInfoToServer()
                                                        handleReloadActivityEditorPage()
                                                        reloadEditFieldPage()
                                                        reloadEditFieldOptionsPage()
                                                      }
                                                      if (selected == '下移') {
                                                        let t = item.options[i].options[i1]
                                                        item.options[i].options[i1] = item.options[i].options[i1 + 1]
                                                        item.options[i].options[i1 + 1] = t
                                                        await handleSubmitItemInfoToServer()
                                                        handleReloadActivityEditorPage()
                                                        reloadEditFieldPage()
                                                        reloadEditFieldOptionsPage()
                                                      }
                                                      if (selected == '修改') {
                                                        tool.controlInput('修改选项内容', '', 'singleText', item.options[i].options[i1], async (value, done) => {
                                                          item.options[i].options[i1] = value
                                                          await handleSubmitItemInfoToServer()
                                                          handleReloadActivityEditorPage()
                                                          reloadEditFieldPage()
                                                          reloadEditFieldOptionsPage()
                                                          done()
                                                        }, (value) => {
                                                          if (value.length == 0) throw '选项不能为空'
                                                          for (let i2 = 0; i2 < item.options[i].options.length; i2++)if (item.options[i].options[i2] == item.options[i].options[i1]) throw '选项未改动或与其他选项重复'
                                                        })
                                                      }
                                                      if (selected == '删除') {
                                                        if (item.options[i].options.length == 1) {
                                                          tool.handleShowToast('至少有一个选项', 'error')
                                                          return
                                                        }
                                                        tool.handleShowModel('是否删除此选项？', true, async () => {
                                                          item.options[i].options = [...item.options[i].options.slice(0, i1), ...item.options[i].options.slice(i1 + 1)]
                                                          await handleSubmitItemInfoToServer()
                                                          handleReloadActivityEditorPage()
                                                          reloadEditFieldPage()
                                                          reloadEditFieldOptionsPage()
                                                        })
                                                      }
                                                    }
                                                  })
                                                }
                                              })
                                            }
                                            re = [
                                              {
                                                list: re
                                              },
                                              {
                                                title: '操作',
                                                list: [
                                                  {
                                                    title: '添加',
                                                    icon: 'add',
                                                    callBack: async () => {
                                                      tool.controlInput('添加选项', '', 'singleText', '', async (value, done) => {
                                                        item.options[i].options.push(value)
                                                        await handleSubmitItemInfoToServer()
                                                        handleReloadActivityEditorPage()
                                                        reloadEditFieldPage()
                                                        reloadEditFieldOptionsPage()
                                                        done()
                                                      }, (value) => {
                                                        if (value.length == 0) throw '选项不能为空'
                                                        for (let i2 = 0; i2 < item.options[i].options.length; i2++)if (item.options[i].options[i2] == value) throw '与已有选项重复'
                                                      })
                                                    }
                                                  }
                                                ]
                                              }
                                            ]
                                            return re
                                          })
                                        }
                                      }
                                    ]
                                  }
                                  return []
                                })
                              ]
                            }
                          ]
                        })
                      }
                      if (e === 2) {
                        item.options[i].required = !item.options[i].required
                        await handleSubmitItemInfoToServer()
                        handleReloadActivityEditorPage()
                      }
                    }
                  })
                }
              })
            }
            re.push({
              title: '添加',
              icon: 'add',
              callBack: async () => {
                let form = {
                  title: '',
                  type: '文本',
                  required: false
                }
                tool.controlSettingsPage('添加字段', async (reloadAddOptionsPage) => {
                  let re = [
                    {
                      list: [
                        {
                          title: '字段名称',
                          right: {
                            type: 'text',
                            value: form.title
                          },
                          callBack: async () => {
                            tool.controlInput('编辑字段名称', '', 'singleText', form.title, async (value, done) => {
                              form.title = value
                              reloadAddOptionsPage()
                              done()
                            }, (value) => {
                              if (!value) throw '字段名称不能为空'
                            })
                          }
                        },
                        {
                          title: '类型',
                          right: {
                            type: 'text',
                            value: form.type
                          },
                          callBack: async () => {
                            wx.showActionSheet({
                              itemList: ['文本', '选项'],
                              success: (e) => {
                                e = e.tapIndex
                                if (e === 0) {
                                  form.type = '文本'
                                  reloadAddOptionsPage()
                                }
                                if (e === 1) {
                                  form.type = '选项'
                                  reloadAddOptionsPage()
                                }
                              }
                            })
                          }
                        },
                        {
                          title: '必填（选）',
                          right: {
                            type: 'switch',
                            value: form.required
                          },
                          callBack: async (e, value) => {
                            form.required = value
                            reloadAddOptionsPage()
                          }
                        }
                      ]
                    },
                    {
                      title: '操作',
                      list: [
                        {
                          title: '确认',
                          icon: 'confirm',
                          callBack: async () => {
                            if (form.title == '') {
                              tool.handleShowToast('字段名称不能为空', 'error')
                              return
                            }
                            if (form.type == '文本') {
                              form.limit = 25
                            }
                            if (form.type == '选项') {
                              form.options = []
                            }
                            item.options.push(form)
                            await handleSubmitItemInfoToServer()
                            handleReloadActivityEditorPage()
                            wx.navigateBack()
                          }
                        }
                      ]
                    }
                  ]

                  return re
                })
              }
            })
            return re
          })
        },
        ...(await tool.execFunc(() => {
          if (activityId) return [{
            title: '操作',
            list: [
              {
                title: '生成二维码',
                icon: 'add',
                callBack: async () => {
                  let re = await tool.getQRCode(`pages/index/index?type=share&isPro=${item.isPro ? true : false}&id=${item.id}`)
                  wx.previewImage({
                    urls: [re],
                  })
                }
              },
              {
                title: `删除当前活动`,
                icon: 'delete',
                callBack: async () => {
                  tool.handleShowModel('是否删除当前活动？', true, async () => {
                    let re = await tool.requestData('/activity/delete', {
                      id: activityId
                    })
                    if (re.status) {
                      tool.handleShowToast('成功', 'success')
                      wx.navigateBack()
                    } else {
                      tool.handleShowToast(re.content)
                    }
                  })
                }
              }
            ]
          }]
          return [{
            title: '操作',
            list: [
              {
                title: `${activityId ? '保存更改' : '保存活动信息'}`,
                icon: '保存',
                callBack: async () => {
                  await handleAddToServer()
                  wx.navigateBack()
                }
              }
            ]
          }]
        }))
      ]

      if (activityId) {
        re1 = [
          {
            list: [
              {
                title: 'ID',
                right: {
                  type: 'text',
                  value: item.id
                },
                disabled: true
              },
              {
                title: '参加人数',
                right: {
                  type: 'text',
                  value: item.joinedUserCount
                },
                disabled: true
              },
              {
                title: '创建时间',
                right: {
                  type: 'text',
                  value: tool.formatTimeNew(new Date(item.createdAt))
                },
                disabled: true
              },
              {
                title: '更新时间',
                right: {
                  type: 'text',
                  value: tool.formatTimeNew(new Date(item.updatedAt))
                },
                disabled: true
              },
            ]
          },
          ...re1
        ]
      }

      return re1
    })
  },
  formatDateTime(date) {
    date = new Date(date)
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从 0 开始的
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },
  controlRichTextEditor(title = '', defaultValue = '', callBack = async () => { }) {
    store.setItem('richTextPage', { title, defaultValue })
    store.setItem('richTextEditorCallBack', callBack)
    wx.navigateTo({
      url: '/pages/richTextEditor/richTextEditor',
    })
  },
  convertImageToBase64(filePath) {
    return new Promise((resolve, reject) => {
      const fs = wx.getFileSystemManager();

      // 读取图片文件的类型（后缀）
      const extension = filePath.split('.').pop().toLowerCase();
      const imageType = extension === 'jpg' ? 'jpeg' : extension; // 处理jpg格式为jpeg

      // 读取图片文件为二进制数据
      fs.readFile({
        filePath: filePath,
        encoding: 'base64',
        success(res) {
          // 拼接成data:image/[image format];base64,[base64 data] 格式
          const base64Data = `data:image/${imageType};base64,${res.data}`;
          resolve(base64Data);
        },
        fail(err) {
          // 读取失败时返回错误
          reject(err);
        }
      });
    });
  },
  createTempFile(content, suffix = '.txt') {
    try {
      return new Promise((resolve, reject) => {
        const tempFilePath = `${wx.env.USER_DATA_PATH}/temp${suffix}`;
        console.log(tempFilePath)
        const fs = wx.getFileSystemManager();
        fs.writeFile({
          filePath: tempFilePath,
          data: content,
          encoding: 'utf8',
          success: (res) => {
            console.log('文件写入成功', res);
            resolve(tempFilePath);
          },
          fail: (err) => {
            console.error('文件写入失败', err);
            reject(err);
          }
        });
      });
    } catch (error) {
      console.log(error)
    }

  },
  async controlProductDetailPage(id = undefined) {
    if (!id) return
    let re = await tool.requestData('/product/getSingleInfo', { id }, 'get')
    if (re.status) {
      store.setItem('controlProductDetailPage', re.data)
      wx.navigateTo({
        url: '/pages/productDetail/productDetail',
      })
    } else {
      tool.handleShowToast(re.content, 'error')
    }
  },
  controlColorEditor(r, g, b, callBack = () => { }) {
    tool.controlSettingsPage('编辑颜色', (handleReloadColorEditorPage) => {
      return [
        {
          list: [
            {
              title: '预览',
              right: {
                type: 'colorPreview',
                value: `rgb(${r},${g},${b})`
              },
              disabled: true
            }
          ]
        },
        {
          title: '分量',
          list: [
            {
              title: '红',
              right: {
                type: 'text',
                value: r
              },
              callBack: () => {
                tool.controlInput('编辑红色', '', 'number', r, (value, done) => {
                  r = value
                  done()
                  handleReloadColorEditorPage()
                }, (value) => {
                  value = parseInt(value)
                  if (isNaN(value)) throw new Error('红色值应为不小于0且不大于255的整数')
                  if (value < 0 || value > 255) {
                    throw new Error('红色值应为不小于0且不大于255的整数')
                  }
                })
              }
            },
            {
              title: '绿',
              right: {
                type: 'text',
                value: g
              },
              callBack: () => {
                tool.controlInput('编辑绿色', '', 'number', g, (value, done) => {
                  g = value
                  done()
                  handleReloadColorEditorPage()
                }, (value) => {
                  value = parseInt(value)
                  if (isNaN(value)) throw new Error('绿色值应为不小于0且不大于255的整数')
                  if (value < 0 || value > 255) {
                    throw new Error('绿色值应为不小于0且不大于255的整数')
                  }
                })
              }
            },
            {
              title: '蓝',
              right: {
                type: 'text',
                value: b
              },
              callBack: () => {
                tool.controlInput('编辑蓝色', '', 'number', b, (value, done) => {
                  b = value
                  done()
                  handleReloadColorEditorPage()
                }, (value) => {
                  value = parseInt(value)
                  if (isNaN(value)) throw new Error('蓝色值应为不小于0且不大于255的整数')
                  if (value < 0 || value > 255) {
                    throw new Error('蓝色值应为不小于0且不大于255的整数')
                  }
                })
              }
            }
          ]
        },
        {
          title: '操作',
          list: [
            {
              title: '保存',
              icon: '保存',
              callBack: async () => {
                try {
                  callBack(r, g, b)
                  wx.navigateBack()
                } catch (error) {
                  console.log(error)
                }
              }
            }
          ]
        }
      ]
    })
  },
  async flow(main = async () => { }, handleError = async () => { }) {
    const te = (str) => {
      throw str
    }
    try {
      await main(te)
    } catch (error) {
      await handleError(error.toString())
    }
  },
  async handleShowProductActivityDetailPage(isPro = true, id = undefined) {
    if (id == undefined) {
      tool.handleShowModel('ID错误')
      return
    }


    let data
    if (isPro) {
      let re = await tool.requestData('/product/getSingleInfo', {
        id: id
      }, 'get')
      if (re.status) {
        data = re.data
      } else {
        tool.handleShowToast(re.content, 'error')
        return
      }
    } else {
      let re = await tool.requestData('/activity/getSingleInfo', {
        id: id
      }, 'get')
      if (re.status) {
        data = re.data
      } else {
        tool.handleShowToast(re.content, 'error')
        return
      }
    }

    store.setItem('detailPageData', {
      isPro,
      data
    })
    wx.navigateTo({
      url: '/pages/detailPage/detailPage'
    })
  },
  async getContent(fileName) {
    let re = await tool.requestData('/getTextFileContent', {
      fileName
    }, 'get')
    if (re.status) return re.data
    return ''
  },
  async handleAddToCart(isPro = 1, id = undefined, num = 0, price = 0, options = {}) {
    if (store.getItem('userData') == undefined) {
      tool.handleNotLogin()
      return
    }
    let re = await tool.requestData('/cart/add', {
      openId: store.getItem('userData').openId,
      isPro,
      id,
      num,
      price,
      options: JSON.stringify(options)
    })
    if (re.status) {
      tool.handleShowToast('成功')
      return true
    } else {
      tool.handleShowToast(re.content, 'error')
      return false
    }
  },
  handleShowCart(show) {
    if (store.getItem('userData') == undefined) {
      tool.handleNotLogin()
      return
    }
    store.setItem('showCart', !show)
  },
  getSinglePrice(item, options, num) {
    let re = item.price
    for (let i = 0; i < Object.keys(options).length; i++) {
      let key = Object.keys(options)[i]
      let value = options[key]
      if (!item.options) continue
      for (let i1 = 0; i1 < item.options.length; i1++) {
        if (item.options[i1].title == key) {
          if (item.options[i1].items.indexOf(value) != -1) {
            let ind = item.options[i1].items.indexOf(value)
            re += item.options[i1].prices[ind]
          }
        }
      }
    }
    return re * num
  },
  getPageByPageSize(size, total) {
    return parseInt(total / size) + ((total % size) ? 1 : 0)
  },
  async pay(price, desc, orderNo = undefined) {
    let re = await tool.requestData('/pay/createOrder', {
      code: await tool.getLoginCode(),
      price: price,
      desc,
      orderNo,
      direct: orderNo ? 1 : 0
    })
    if (re.status) {
      console.log({
        nonceStr: re.data.nonce_str,
        package: `prepay_id=${re.data.prepay_id}`,
        paySign: re.data.sign,
        signType: "MD5",
        timeStamp: Math.floor(Date.now() / 1000).toString(),
        fail: (e) => {
          console.log(e)
        }
      })

      wx.requestPayment({
        nonceStr: re.data.nonce_str,
        package: `prepay_id=${re.data.prepay_id}`,
        paySign: re.data.paySign,
        signType: "MD5",
        timeStamp: re.data.timeStamp,
        fail: (e) => {
          console.log(e)
        }
      })

    } else {
      tool.handleShowToast('订单创建失败', 'error')
    }
  },
  handleShowPayPage(itemList = []) {
    store.setItem('payPage', itemList)
    wx.navigateTo({
      url: '/pages/pay/pay',
    })
  },
  async handleUpdateCartNum() {
    let re = await tool.requestData('/cart/getList', {
      openId: store.getItem('userData').openId
    }, 'get', false)
    if (re.status) {
      store.setItem('cartNum', re.data.selectable.length)
      store.setItem('cartList', re.data.selectable)
    }
  },
  formatPrice(p) {
    return `${p / 100}${(p / 100).toString().split('.')[1] == undefined ? '' : ((p / 100).toString().split('.')[1].length == 1 ? '0' : '')}`
  },
  async showMyOrderPage() {
    let pageSize = {
      page: 1,
      size: 5,
      total: 0
    }
    let re = await tool.requestData('/order/getList', {
      openId: store.getItem('userData').openId,
      ...pageSize
    })
    if (re.status) {
      if (re.data.list.length == 0) {
        tool.handleShowToast('无订单')
        return
      }
    } else {
      tool.handleShowToast(re.content)
      return
    }
    tool.controlSettingsPage('我的订单', async (reloadMyOrderPage, myOrderPageToTop) => {
      let sett = []
      let re = await tool.requestData('/order/getList', {
        openId: store.getItem('userData').openId,
        ...pageSize
      })
      if (re.status) {
        pageSize.total = re.data.total
        re = re.data.list
        if (!re.length) {
          wx.navigateBack()
          await tool.wait(0.5)
          tool.handleShowToast(re.content)
          return
        }
        let t = []
        for (let i = 0; i < re.length; i++) {
          let on = re[i].orderNo
          t.push({
            title: re[i].orderNo,
            list: [
              {
                title: '状态',
                right: {
                  type: 'text',
                  value: re[i].status_read
                },
                disabled: true
              },
              {
                title: '取单码',
                right: {
                  type: 'text',
                  value: re[i].code
                },
                disabled: true
              },
              {
                title: '创建时间',
                right: {
                  type: 'text',
                  value: re[i].paidAt_read
                },
                disabled: true
              },
              {
                title: '支付金额',
                right: {
                  type: 'text',
                  value: re[i].totalPrice_read
                },
                disabled: true
              },
              {
                title: '地址',
                right: {
                  type: 'text',
                  value: re[i].address
                },
                disabled: true
              },
              {
                title: '商品列表',
                callBack: async () => {
                  tool.showItemList(on)
                }
              },
              {
                title: '详情页面',
                callBack: async () => {
                  tool.showOrderStatusPage(re[i].orderNo)
                }
              }
            ]
          })
        }
        sett = t
      } else {
        tool.handleShowToast(re.content)
        await tool.wait(0.3)
        wx.navigateBack()
      }
      sett.push({
        title: `${pageSize.page} / ${tool.getPageByPageSize(pageSize.size, pageSize.total)}`,
        list: [
          ...(await tool.execFunc(async () => {
            if (pageSize.page == 1) return []
            return [
              {
                title: '第一页',
                callBack: async () => {
                  pageSize.page = 1
                  await reloadMyOrderPage()
                  myOrderPageToTop()
                }
              },
              {
                title: '上一页',
                callBack: async () => {
                  pageSize.page--
                  await reloadMyOrderPage()
                  myOrderPageToTop()
                }
              },
            ]
          })),
          ...(await tool.execFunc(async () => {
            if (pageSize.page == tool.getPageByPageSize(pageSize.size, pageSize.total)) return []
            return [
              {
                title: '下一页',
                callBack: async () => {
                  pageSize.page++
                  await reloadMyOrderPage()
                  myOrderPageToTop()
                }
              },
              {
                title: '最后一页',
                callBack: async () => {
                  pageSize.page = tool.getPageByPageSize(pageSize.size, pageSize.total)
                  await reloadMyOrderPage()
                  myOrderPageToTop()
                }
              },
            ]
          })),
        ]
      })
      return sett
    })
  },
  webSocket: {
    socketTask: undefined,
    isConnected: true,
    _messageCallBacks: [],
    onMessage(key = '', callBack = () => { }) {
      this._messageCallBacks.push({
        key, callBack
      })
    },
    _connectedCallBacks: [],
    onConnected(callBack = async () => { }) {
      this._connectedCallBacks.push(callBack)
    },
    _closedCallBacks: [],
    onClosed(callBack = async () => { }) {
      this._closedCallBacks.push(callBack)
    },
    sendMessage(key, value) {
      if (this.isConnected == false) throw 'WS未连接'
      wx.sendSocketMessage({
        data: JSON.stringify({
          message: {
            key,
            value
          }
        })
      });
    },
    connect() {
      // if (store.getItem('userData') === undefined || !store.getItem('userData').isAdmin) {
      //   console.log('   WS - 普通用户无法建立WS连接')
      //   return
      // }
      try {

      } catch (error) {
        console.log(error)
      }
      this.socketTask = wx.connectSocket({
        url: config.wsServerURL,
        success: function () {
          console.log('   WS - 连接成功');
        },
        fail: function (err) {
          console.error('   WS - 连接失败', err);
        }
      })
      this.socketTask.onOpen(() => {
        console.log('   WS - 已打开');
        this.isConnected = true
        let time = (new Date()).toString()
        store.setItem('webSocketAllowTimeStr', time)
        this.sendMessage('connected', {
          openId: store.getItem('userData').openId,
          time
        })
        for (let i = 0; i < this._connectedCallBacks.length; i++) {
          try {
            this._connectedCallBacks[i]()
          } catch (error) {
            console.log(error)
          }
        }
      });

      // 监听 WebSocket 消息事件
      this.socketTask.onMessage((res) => {
        try {
          res.data = JSON.parse(res.data)
        } catch (error) {

        }
        for (let i = 0; i < this._messageCallBacks.length; i++) {
          if (this._messageCallBacks[i].key !== res.data.key) continue
          try {
            this._messageCallBacks[i].callBack(res.data.value)
          } catch (error) {
            console.log(error)
          }
        }
        console.log('   WS - 接收', res.data);
      });

      // 监听 WebSocket 错误事件
      this.socketTask.onError((err) => {
        console.error('   WS - 错误', err);
      });

      // 监听 WebSocket 关闭事件
      this.socketTask.onClose(() => {
        console.log('   WS - 已关闭');
        this.isConnected = false
        for (let i = 0; i < this._closedCallBacks.length; i++) {
          try {
            this._closedCallBacks[i]()
          } catch (error) {
            console.log(error)
          }
        }
      });
    }
  },
  showOrdersSettingsPage(status = 0) {
    const handleShowPage = async (status) => {
      const pageSize = {
        page: 1,
        size: 5,
        total: 0
      }
      let e = ['正在备餐', '正在配送', '等待取餐']
      let re = await tool.requestData('/order/getPreToDo', {
        ...pageSize,
        status
      })
      if (re.status) {
        if (re.data.list.length == 0) {
          tool.handleShowToast('无订单')
          return
        }
      } else {
        tool.handleShowToast(re.content)
        return
      }
      tool.controlSettingsPage(`${status == 5 ? '全部' : (e[status - 1])}订单`, async (reloadPreToDoPage, preToDoPageToTop) => {
        let re = await tool.requestData('/order/getPreToDo', {
          ...pageSize,
          status
        })
        if (re.status) {

          pageSize.total = re.data.total
          re.data = re.data.list
          if (re.data.length == 0 && pageSize.page > 1) {
            pageSize.page--
            reloadPreToDoPage()
            preToDoPageToTop()
            return
          }
          let sett = []
          for (let i = 0; i < re.data.length; i++) {
            let orderNo = re.data[i].orderNo
            sett.push({
              title: re.data[i].createdAt_read,
              list: [
                {
                  title: '用户名',
                  right: {
                    type: 'text',
                    value: re.data[i].username,
                  },
                  disabled: true
                },
                {
                  title: '手机号',
                  right: {
                    type: 'text',
                    value: re.data[i].phone,
                  },
                  callBack: () => {
                    wx.makePhoneCall({
                      phoneNumber: `${re.data[i].phone}`,

                      complete(e) {

                      }
                    })
                  }
                },
                {
                  title: '总共支付',
                  right: {
                    type: 'text',
                    value: re.data[i].price_read,
                  },
                  disabled: true
                },
                {
                  title: '地址',
                  right: {
                    type: 'text',
                    value: re.data[i].address,
                  },
                  disabled: true
                },
                {
                  title: '取单码',
                  right: {
                    type: 'text',
                    value: re.data[i].code,
                  },
                  disabled: true
                },
                {
                  title: '商品列表',
                  callBack: async () => {
                    tool.showItemList(re.data[i].orderNo)
                  }
                },
                {
                  title: '修改状态',
                  callBack: async () => {
                    tool.handleChangeOrderStatus(re.data[i].orderNo)
                  }
                }
              ]
            })
          }

          sett.push({
            title: `${pageSize.page}/${tool.getPageByPageSize(pageSize.size, pageSize.total)}`,
            list: (await tool.execFunc(async () => {
              let re = []
              if (pageSize.page > 1) {
                re.push({
                  title: '第一页',
                  callBack: async () => {
                    pageSize.page = 1
                    reloadPreToDoPage()
                    preToDoPageToTop()
                  }
                })
                re.push({
                  title: '上一页',
                  callBack: async () => {
                    pageSize.page--
                    reloadPreToDoPage()
                    preToDoPageToTop()
                  }
                })
              }
              if (pageSize.page < tool.getPageByPageSize(pageSize.size, pageSize.total)) {
                re.push({
                  title: '下一页',
                  callBack: async () => {
                    pageSize.page++
                    reloadPreToDoPage()
                    preToDoPageToTop()
                  }
                })
                re.push({
                  title: '最后一页',
                  callBack: async () => {
                    pageSize.page = tool.getPageByPageSize(pageSize.size, pageSize.total)
                    reloadPreToDoPage()
                    preToDoPageToTop()
                  }
                })
              }
              return re
            }))
          })

          return sett

        } else {
          wx.navigateBack()
          await tool.wait(0.3)
          tool.handleShowToast(re.content, 'error')
        }
      })
    }
    if (status) {
      handleShowPage(status)
      return
    }
    wx.showActionSheet({
      itemList: ['正在备餐', '正在配送', '等待取餐'],
      success: async (e) => {
        e = e.tapIndex
        handleShowPage(e + 1)
      }
    })
  },
  async showItemList(on) {
    let re = await tool.requestData('/order/getItemList', {
      orderNo: on
    })
    if (re.status) {
      re = re.data
      let t = []
      for (let i = 0; i < re.length; i++) {
        t.push({
          title: `${re[i].itemInfo.title}${re[i].info === undefined ? `（已下架）` : ''}`,
          list: [
            {
              title: '原价',
              right: {
                type: 'text',
                value: re[i].currentPrice_read
              }
            },
            {
              title: '选项',
              right: {
                type: 'text',
                value: re[i].options_read
              }
            },
            {
              title: '原价（带有选项和数量）',
              right: {
                type: 'text',
                value: re[i].currentPriceWithOptionsAndNum_read
              }
            },
            {
              title: '折扣',
              right: {
                type: 'text',
                value: re[i].discount_read
              }
            },
            {
              title: '折扣价',
              right: {
                type: 'text',
                value: re[i].currentPriceWithDiscount_read
              }
            },
            ...(await tool.execFunc(async () => {
              if (re[i].info === undefined) return []
              return [
                {
                  title: '详情页',
                  callBack: async () => {
                    tool.handleShowProductActivityDetailPage(re[i].isPro, re[i].itemId)
                  }
                }
              ]
            }))
          ]
        })
      }

      tool.controlSettingsPage(`商品列表（${on.slice(25, 29)}）`, t)
    } else {
      tool.handleShowToast(re.content, 'error')
    }
  },
  async showActivityUserList(id) {
    let re = await tool.requestData('/activity/getJoinedUserList', {
      id
    })
    if (re.status) {
      if (re.data.length == 0) {
        tool.handleShowToast('参与名单为空', 'error')
        return
      }
      let sett = []
      for (let i = 0; i < re.data.length; i++) {
        sett.push({
          title: re.data[i].username,
          list: [
            {
              title: '联系电话',
              right: {
                type: 'text',
                value: re.data[i].phone
              },
              callBack: async () => {
                wx.makePhoneCall({
                  phoneNumber: re.data[i].phone,
                })
              }
            },
            ...await tool.execFunc(async () => {
              if (re.data[i].options == null) return []
              let ls = []
              for (let i1 = 0; i1 < Object.keys(re.data[i].options).length; i1++) {
                let key = Object.keys(re.data[i].options)[i1]
                let value = re.data[i].options[Object.keys(re.data[i].options)[i1]]
                ls.push({
                  title: key,
                  right: {
                    type: 'text',
                    value
                  },
                  disabled: true
                })
              }
              return ls
            }),
            {
              title: '用户信息',
              callBack: async () => {
                tool.handleShowUserInfoPage(re.data[i].openId)
              }
            }
          ]
        })
      }
      tool.controlSettingsPage('参与名单', sett)
    } else {
      tool.handleShowToast(re.content)
    }
  },
  connectAndPrintLabel(singleLabelData) {
    // 初始化打印机 API
    const lpapi = LPAPIFactory.getInstance({
      showLog: 4, // 日志级别
    });
    // 搜索蓝牙打印机
    function startDiscovery() {
      console.log("正在搜索打印机...");
      return new Promise((resolve) => {
        lpapi.startBleDiscovery({
          timeout: 5000,
          deviceFound: (devices) => {
            if (devices && devices.length > 0) {
              console.log("发现打印机:", devices);
              resolve(devices[0]); // 默认选择第一个打印机
            } else {
              console.warn("未发现打印机");
              resolve(null);
            }
          },
          adapterStateChange: (result) => {
            if (!result.discovering) {
              console.log("搜索结束");
            }
          },
        });
      });
    }

    // 连接打印机
    function openPrinter(device) {
      return new Promise((resolve, reject) => {
        if (device && device.deviceId) {
          console.log("正在连接打印机...");
          lpapi.openPrinter({
            name: device.name,
            deviceId: device.deviceId,
            success: () => {
              console.log("打印机连接成功！");
              resolve(true);
            },
            fail: (resp) => {
              console.error("打印机连接失败", resp);
              reject(false);
            },
          });
        } else {
          console.warn("无有效打印机");
          reject(false);
        }
      });
    }

    // 打印文本
    function printText(content) {

      let order = content
      let currentOrder = content

      const api = lpapi;
      //
      const labelWidth = 40;
      const labelHeight = 31.5;
      const padding = 2
      let pos = 0;
      // 创建 40mm x 30mm 大小标签的打印任务；
      api.startJob({
        width: labelWidth,
        height: labelHeight,
        jobName: 'lpapi-ble',
      });
      if (currentOrder.item.index == 1) {
        api.drawLine({
          x1: 0,
          y1: 1,
          x2: labelWidth,
          y2: 1,
          lineWidth: 0.2,
        });
      }
      api.draw1DBarcode({
        text: currentOrder.item.barCode,
        x: padding,
        y: padding,
        width: labelWidth - padding * 2,
        height: 4,
        textHeight: 2,
        type: 26,
      });
      api.drawText({
        text: `${order.code}-${currentOrder.item.index}/${order.proNum}`,
        x: padding + 14,
        y: padding + 5.5,
        fontHeight: 4.5,
      });
      api.drawText({
        text: `本单共支付`,
        x: padding,
        y: padding + 5,
        fontHeight: 2,
      });
      api.drawText({
        text: `￥${currentOrder.totalPricePrint}`,
        x: padding,
        y: padding + 5 + 2.5,
        fontHeight: 2,
      });
      let tt = `${currentOrder.item.itemInfo.title} ${currentOrder.item.optionsPrint}`
      api.drawText({
        text: tt,
        x: padding,
        y: padding + 10.5,
        width: labelWidth - padding * 2,
        fontHeight: 2.5,
      });
      api.drawText({
        text: `${currentOrder.item.discount === undefined ? `` : `${currentOrder.item.discount} `}￥${currentOrder.item.priceWithDiscountPrint} 支付于${currentOrder.paidAt}
${currentOrder.item.address} ${currentOrder.item.phone}
${currentOrder.item.text}`,
        x: padding,
        y: padding + 10.5 + ((parseInt(tool.calculateStringWeight(tt)) / 14) + ((tool.calculateStringWeight(tt) % 14) ? 1 : 0)) * 2.5 + 1,
        width: labelWidth - padding * 2,
        fontHeight: 2,
      });
      api.commitJob({
        gapType: 255,
        darkness: 255,
      }).then((resp) => {
        console.log(1234)
      });
    }

    return new Promise((resolve, reject) => {
      startDiscovery()
        .then((device) => openPrinter(device))
        .then(() => printText(singleLabelData)).then(() => {
          resolve()
        })
        .catch((err) => {
          resolve()
          console.error("操作失败:", err);
        });
    })
    // 执行流程

  },
  async printLabel(orderNo, select = false) {
    let re = await tool.requestData('/order/getPrintLabelInfo', {
      orderNo,
      f: select ? true : undefined
    }, 'get', false)
    if (re.status) {

    } else {
      if (select) tool.handleShowToast(re.content, 'error')
      return
    }

    // tool.handleShowModel(`打印订单${orderNo}`)

    await tool.requestData('/order/setPrinted', {
      orderNo
    }, 'post', false)

    // return

    console.log(re.data)
    console.log(JSON.stringify(re.data))
    // this.connectAndPrintLabel()
    let order = re.data
    const printOrderLabelData = []
    for (let i = 0; i < order.items.length; i++) {
      let currentItem = JSON.parse(JSON.stringify(order.items[i]))
      let order_c = JSON.parse(JSON.stringify(order))
      delete order_c.items
      delete order_c.userInfo
      currentItem.index = i + 1
      printOrderLabelData.push({
        ...order_c,
        item: currentItem
      })
    }
    if (select) {
      tool.controlSettingsPage('选择要打印的标签', async () => {
        let ls = [
          {
            title: '全部',
            callBack: async () => {
              for (let i = 0; i < printOrderLabelData.length; i++) {
                printTaskHandler.add(printOrderLabelData[i])
              }
              await tool.wait(3)
            }
          },
        ]
        for (let i = 0; i < printOrderLabelData.length; i++) {
          ls.push({
            title: `${printOrderLabelData[i].code}-${printOrderLabelData[i].item.index}/${printOrderLabelData[i].proNum}`,
            callBack: async () => {
              printTaskHandler.add(printOrderLabelData[i])
              await tool.wait(3)
            }
          })
        }
        return [
          {
            list: ls
          }
        ]
      })
    } else {
      for (let i = 0; i < printOrderLabelData.length; i++) {
        printTaskHandler.add(printOrderLabelData[i])
      }
    }

  },
  calculateStringWeight(str) {
    let totalWeight = 0;

    for (let char of str) {
      // 判断是否是汉字
      if (/[\u4e00-\u9fa5]/.test(char)) {
        totalWeight += 1;
      }
      // 判断是否是数字或字母
      else if (/[a-zA-Z0-9]/.test(char)) {
        totalWeight += 0.5;
      }
    }

    return totalWeight;
  },
  showOrderStatusPage(orderNo) {
    store.setItem('orderDetailPage', orderNo)
    wx.navigateTo({
      url: '/pages/pay/pay',
    })
  },
  async handleChangeOrderStatus(orderNo) {
    let re = await tool.requestData('/order/getStatus', {
      orderNo
    }, 'get')
    if (re.status) {
      let ls = [
        {
          title: '正在备餐',
          code: 1
        }
      ]
      if (re.data.type == 3) {
        ls.push({
          title: '正在配送',
          code: 2
        })
      }
      if (re.data.type == 2) {
        ls.push({
          title: '等待取餐',
          code: 3
        })
      }
      ls.push({
        title: '已完成',
        code: 4
      })
      wx.showActionSheet({
        itemList: (() => {
          let re = []
          for (let i = 0; i < ls.length; i++) {
            re.push(ls[i].title)
          }
          return re
        })(),
        success: async (e) => {
          e = e.tapIndex
          let re = await tool.requestData('/order/updateStatus', {
            orderNo: orderNo,
            status: ls[e].code
          })
          if (re.status) {
            reloadPreToDoPage()
            preToDoPageToTop()
          } else {
            tool.handleShowToast(re.content, 'error')
          }
        }
      })
    } else {
      tool.handleShowToast(re.content, 'error')
    }
  },
  async handleShowUserInfoPage(openId) {
    let re = await tool.requestData('/user/getSingleInfo', {
      openId
    }, 'get')
    if (re.status) {
      let item = re.data
      tool.controlSettingsPage(item.username, async (reloadUserInfoPage) => {
        let re = [
          {
            title: '用户名',
            right: {
              type: 'text',
              value: item.username
            },
            disabled: true
          },
          {
            title: '头像',
            right: {
              type: 'image',
              src: item.avatar
            },
            disabled: true
          },
          {
            title: '手机号',
            right: {
              type: 'text',
              value: item.phone
            },
            disabled: true
          },
          {
            title: '性别',
            right: {
              type: 'text',
              value: item.sex == 0 ? '保密' : (item.sex == 1 ? '男' : '女')
            },
            disabled: true
          },
          {
            title: '生日',
            right: {
              type: 'text',
              value: item.birthday
            },
            disabled: true
          },
          {
            title: '地址',
            right: {
              type: 'text',
              value: item.address
            },
            disabled: true
          },
          {
            title: 'PLUS会员',
            right: {
              type: 'text',
              value: item.isVIP ? '是' : '否'
            },
            disabled: true
          },
          {
            title: 'PLUS会员截止日期',
            right: {
              type: 'text',
              value: item.vipEndTime_read
            },
            disabled: true
          },
          {
            title: '管理员',
            right: {
              type: 'text',
              value: item.isAdmin ? '是' : '否'
            },
            disabled: true
          },
        ]

        return [
          {
            title: '个人信息',
            list: re,
          },
          {
            title: '操作',
            list: [
              {
                title: item.isAdmin ? '取消管理员权限' : '设为管理员',
                callBack: async () => {
                  let re = await tool.requestData('/user/setAdmin', {
                    userId: item.id,
                    is: item.isAdmin ? 0 : 1,
                    openId: item.openId
                  })
                  if (re.status) {
                    item.isAdmin = !item.isAdmin
                    tool.handleShowToast('成功', 'success')
                    reloadUserInfoPage()
                  } else {
                    tool.handleShowToast(re.content, 'error')
                  }
                }
              },
              {
                title: '优惠券',
                callBack: async () => {

                  tool.controlSettingsPage(`${item.username}的优惠券`, async (reloadCouponsPage) => {
                    let re = await tool.requestData('/coupons/getList', {
                      openId: item.openId,
                      showAll: true
                    }, 'get')
                    if (re.status) {
                      re = re.data
                    } else {
                      tool.handleShowToast(re.content, 'error')
                    }

                    let res = []
                    for (let i1 = 0; i1 < re.length; i1++) {
                      res.push({
                        title: re[i1].discount ? `${re[i1].discount / 10}折` : '免费',
                        right: {
                          type: 'text',
                          value: re[i1].endTime == '' ? '永久' : re[i1].endTime
                        },
                        callBack: async () => {
                          let cid = re[i1].id
                          wx.showActionSheet({
                            itemList: ['删除'],
                            success: async (e) => {
                              e = e.tapIndex
                              if (e == 0) {
                                let re = await tool.requestData('/coupons/delete', {
                                  id: cid
                                })
                                if (re.status) {
                                  reloadCouponsPage()
                                  done()
                                } else {
                                  tool.handleShowToast(re.content, 'error')
                                }
                              }
                            }
                          })
                        }
                      })
                    }

                    return [
                      {
                        title: '列表',
                        list: res
                      },
                      {
                        title: "操作",
                        list: [
                          {
                            title: '添加',
                            callBack: async () => {
                              let form = {
                                discount: 90,
                                endTime: ''
                              }
                              tool.controlSettingsPage('添加优惠券', async (reloadAddCouponPage) => {
                                let ls = [
                                  {
                                    list: [
                                      {
                                        title: '折扣',
                                        right: {
                                          type: 'text',
                                          value: form.discount
                                        },
                                        callBack: async () => {
                                          tool.controlInput('折扣', '', 'number', form.discount, async (value, done) => {
                                            form.discount = value
                                            reloadAddCouponPage()
                                            done()
                                          }, (value) => {
                                            value = parseInt(value)
                                            if (isNaN(value)) {
                                              throw '应为不大于100的自然数'
                                            }
                                            if (value < 0 || value > 100) {
                                              throw '应为不大于100的自然数'
                                            }
                                          })
                                        }
                                      },
                                      {
                                        title: '截止时间',
                                        right: {
                                          type: 'text',
                                          value: form.endTime == '' ? '永久' : form.endTime
                                        },
                                        callBack: async () => {
                                          wx.showActionSheet({
                                            itemList: ['设为永久', '选择日期时间'],
                                            success: async (e) => {
                                              e = e.tapIndex
                                              if (e === 0) {
                                                form.endTime = ''
                                                reloadAddCouponPage()
                                              }
                                              if (e === 1) {
                                                tool.controlPicker('选择优惠券失效日期时间', '', 'dateTime', form.endTime, [], async (value, done) => {
                                                  form.endTime = value
                                                  done()
                                                  reloadAddCouponPage()
                                                }, (value) => {
                                                  if (value.match(/[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}/) == null) {
                                                    throw '请选择日期时间'
                                                  }
                                                })
                                              }
                                            }
                                          })
                                        }
                                      }
                                    ]
                                  },
                                  {
                                    title: '操作',
                                    list: [
                                      {
                                        title: '确定',
                                        callBack: async () => {
                                          let re = await tool.requestData('/coupons/add', {
                                            openId: item.openId,
                                            discount: parseInt(form.discount),
                                            endTime: form.endTime
                                          })
                                          if (re.status) {
                                            tool.handleShowToastWithMask('成功')
                                            await tool.wait(0.5)
                                            reloadCouponsPage()
                                            wx.navigateBack()
                                          } else {
                                            tool.handleShowToast(re.content, 'error')
                                          }
                                        }
                                      }
                                    ]
                                  }
                                ]

                                return ls
                              })

                              return
                              tool.controlInput('请输入折扣', '0为免费，45为4.5折', 'number', 90, async (value, done) => {
                                let re = await tool.requestData('/coupons/add', {
                                  openId: item.openId,
                                  discount: parseInt(value)
                                })
                                if (re.status) {
                                  reloadCouponsPage()
                                  done()
                                } else {
                                  tool.handleShowToast(re.content, 'error')
                                }
                              }, (value) => {
                                if (value < 0 || value > 99) {
                                  throw '折扣应不小于0且小于100'
                                }
                              })
                            }
                          }
                        ]
                      }
                    ]
                  })

                }
              },
              // {
              //   title: '删除',
              //   callBack: async () => {
              //     tool.handleShowModel('是否删除此用户？', true, async () => {
              //       let re = await tool.requestData('/user/delete', {
              //         openId: item.openId
              //       })
              //       if (re.status) {
              //         tool.handleShowToastWithMask('成功', 'success', 1000)
              //         await tool.wait(1)
              //         wx.navigateBack()
              //         reloadUserListPage()
              //       } else {
              //         tool.handleShowToast(re.content, 'error')
              //       }
              //     })
              //   }
              // }
            ]
          }
        ]
      })
    } else {
      tool.handleShowToast(re.content, 'error')
    }

  },
  handleCheckForm(form, options) {
    if (!options) return
    for (let i = 0; i < options.length; i++) {
      if (options[i].type == '文本') {
        if (form[options[i].title] === undefined && options[i].required) {
          throw `${options[i].title}为必填项`
        }
        if (form[options[i].title] !== undefined && form[options[i].title].length > options[i].limit) {
          throw `${options[i].title}的长度不能多于${options[i].limit}`
        }
      }
      if (options[i].type == '选项') {
        if (form[options[i].title] === undefined && options[i].required) {
          throw `${options[i].title}为必选项`
        }
      }
    }
  },
  handleShowActivityUserSubmitedForm(title, form) {
    tool.controlSettingsPage(title, async () => {
      let re = []
      for (let i = 0; i < Object.keys(form).length; i++) {
        let key = Object.keys(form)[i]
        let value = form[Object.keys(form)[i]]
        re.push({
          title: key,
          right: {
            type: 'text',
            value
          }
        })
      }
      return [
        {
          list: re
        }
      ]
    })
  },
  async handleShowSelectCouponPage(callBack = undefined) {
    let re = await tool.requestData('/coupons/getList', {
      openId: store.getItem('userData').openId
    }, 'get')
    if (re.status) {
      if (re.data.length == 0) {
        tool.handleShowToast('无更多优惠券', 'error')
        return
      }
    } else {
      tool.handleShowToast(re.content, 'error')
      return
    }
    store.setItem('showSelectCouponPage', {
      callBack,
      list: re.data
    })
    wx.navigateTo({
      url: '/pages/selectCoupon/selectCoupon',
    })
  },
  handleScan() {
    wx.scanCode({
      scanType: 'barCode',
      success: async (e) => {
        if (e.scanType != 'CODABAR') {
          tool.handleShowToast('请重试', 'error')
          return
        }
        e = e.result
        if (e.length != 10) {
          tool.handleShowToast('非本店条形码', 'error')
          return
        }
        let info = {
          totalNo: e.slice(0, 8),
          index: parseInt(e.slice(8, 10))
        }
        let re = await tool.requestData('/order/getOrderNoByTotalNo', {
          totalNo: info.totalNo
        }, 'get')
        if (re.status) {
          re = await tool.requestData('/order/getStatus', {
            orderNo: re.data
          }, 'get')
          if (re.status) {
            re = re.data
            if (re.userInfo.openId != store.getItem('userData').openId && !store.getItem('userData').isAdmin) {
              tool.handleShowToast('这不是您的订单', 'error')
              return
            }
            let ls = [
              ...await (async () => {
                if (re.userInfo.openId == store.getItem('userData').openId) {
                  let ls = []
                  if (re.status == 2 || re.status == 3) {
                    ls.push('确认收货')
                  }
                  ls.push('订单详情页面')
                  return ls
                } else {
                  return []
                }
              })(),
              ...await (async () => {
                if (store.getItem('userData').isAdmin) {
                  return ['拨打电话', '修改状态', '订单详情页面', '查看用户信息']
                } else {
                  return []
                }
              })()
            ]
            wx.showActionSheet({
              itemList: [...new Set(ls)],
              alertText: re.orderNo,
              success: async (e) => {
                e = e.tapIndex
                let selected = ls[e]
                switch (selected) {
                  case '确认收货':
                    let res = await tool.requestData('/order/userConfirm', {
                      openId: store.getItem('userData').openId,
                      orderNo: re.orderNo
                    })
                    if (res.status) {
                      tool.handleShowToast('成功')
                    } else {
                      tool.handleShowToast(res.content, 'error')
                    }
                    break;
                  case '订单信息':
                    tool.showOrderStatusPage(re.orderNo)
                    break
                  case '拨打电话':
                    wx.makePhoneCall({
                      phoneNumber: re.phone,
                    })
                    break
                  case '修改状态':
                    tool.handleChangeOrderStatus(re.orderNo)
                    break
                  case '订单详情页面':
                    tool.showOrderStatusPage(re.orderNo)
                    break
                  case '查看用户信息':
                    tool.handleShowUserInfoPage(re.userInfo.openId)
                    break
                }
              }
            })
          } else {
            tool.handleShowToast(re.content, 'error')
          }
        } else {
          tool.handleShowToast('订单不存在', 'error')
        }
      },
      fail: (e) => {
        console.log(e)
      },
      complete: (e) => {
        console.log(e)
      }
    })
  },
  handleShowShareLinkPage(id, discount) {
    store.setItem('shareLink', { id, discount })
    wx.navigateTo({
      url: `/pages/shareLink/shareLink`,
    })
  },
  async handleUserShareLink(id) {
    let re = await tool.requestData('/shareLink/use', {
      linkId: id,
      userId: store.getItem('userData').id
    }, 'post', false)
    if (re.status) {

    } else {
      throw re.content
    }
  },
  async getQRCode(path = 'pages/index/index') {
    let re = await tool.requestData('/tool/genQRCode', {
      path
    })
    if (re.status) {
      return re.data
    } else {
      throw re.content
    }
  }
}